<template>
  <div>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p class="loading-text">正在加载视频...</p>
    </div>

    <!-- 空数据状态 -->
    <div v-else-if="!currentVideo || Object.keys(currentVideo).length === 0" class="empty-state">
      <i class="far fa-play-circle empty-icon"></i>
      <p class="empty-text">暂无精选视频</p>
    </div>

    <!-- 视频播放器 -->
    <VideoPlayer
      v-else
      :current-video="currentVideo"
      episode-button-text="全集"
      @next-video="nextVideo"
      @prev-video="prevVideo"
      @toggle-like="handleToggleLike"
      @toggle-star="handleToggleStar"
      @toggle-episode-selector="toggleEpisodeSelector"
      @comment-submitted="handleCommentSubmitted"
      @select-episode="onSelectEpisode"
      flag="featured"
    />

    <!-- Toast提示 -->
    <div v-if="showToast" class="toast-message">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { reqFeaturedVideos, toggleEpisodeLike, toggleEpisodeFavorite, reqSubmitEpisodeComment } from '@/apis/video'
import VideoPlayer from '@/components/VideoPlayer.vue'

const router = useRouter()

// 视频相关状态
const currentVideoIndex = ref(0)
const videos = ref([])
const currentVideo = ref({})

// 加载状态
const loading = ref(true)

// 提示消息
const toastMessage = ref('')
const showToast = ref(false)

// 显示提示消息
const showToastMessage = (message) => {
  toastMessage.value = message
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 2000)
}

// 视频切换状态
const isVideoSwitching = ref(false)

const toggleEpisodeSelector = () => {
  router.push(`/player/${currentVideo.value.drama.id}`)
}

/**
 * 加载视频数据
 */
const loadVideos = async () => {
  try {
    loading.value = true
    const response = await reqFeaturedVideos()
    const { episodes } = response.data

    console.log('加载的视频数据:', episodes)

    if (episodes && episodes.length > 0) {
      videos.value = episodes
      updateCurrentVideo()
    } else {
      showToastMessage('暂无精选视频')
    }
  } catch (error) {
    console.error('加载视频失败:', error)
    showToastMessage('加载视频失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 更新当前视频
 */
const updateCurrentVideo = () => {
  if (videos.value.length > 0 && currentVideoIndex.value < videos.value.length) {
    const video = videos.value[currentVideoIndex.value]
    currentVideo.value = video
  }
}

const onSelectEpisode = (data) => {
  const video = videos.value[data.index]
  currentVideo.value = video
}

/**
 * 下一个视频
 */
const nextVideo = () => {
  if (isVideoSwitching.value) return

  if (currentVideoIndex.value < videos.value.length - 1) {
    isVideoSwitching.value = true
    currentVideoIndex.value++
    updateCurrentVideo()

    setTimeout(() => {
      isVideoSwitching.value = false
    }, 500)
  } else {
    showToastMessage('已经是最后一个视频')
  }
}

/**
 * 上一个视频
 */
const prevVideo = () => {
  if (isVideoSwitching.value) return

  if (currentVideoIndex.value > 0) {
    isVideoSwitching.value = true
    currentVideoIndex.value--
    updateCurrentVideo()

    setTimeout(() => {
      isVideoSwitching.value = false
    }, 500)
  } else {
    showToastMessage('已经是第一个视频')
  }
}

/**
 * 处理点赞
 */
const handleToggleLike = async (data) => {
  console.log('点赞状态:', data)

  try {
    // 集数ID
    const episodeId = data.currentVideo.cid
    // 点赞或取消点赞
    const action = data.isLiked ? 'like' : 'unlike'

    // 调用点赞接口
    const res = await toggleEpisodeLike(episodeId, action)
    console.log('点赞接口响应:', res)

    showToastMessage(data.isLiked ? '点赞成功' : '已取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    showToastMessage('操作失败，请稍后重试')
  }
}

/**
 * 处理收藏
 */
const handleToggleStar = async (data) => {
  console.log('收藏状态:', data)

  try {
    // 集数ID
    const episodeId = data.currentVideo.cid
    // 收藏或取消收藏
    const action = data.isLiked ? 'favorite' : 'unfavorite'

    // 调用收藏接口
    const res = await toggleEpisodeFavorite(episodeId, action)
    console.log('收藏接口响应:', res)

    showToastMessage(data.isLiked ? '收藏成功' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    showToastMessage('操作失败，请稍后重试')
  }
}

/**
 * 评论提交后处理
 */
const handleCommentSubmitted = async (data) => {
  console.log('评论已提交:', data)

  try {
    const episodeId = data.video.cid

    const res = await reqSubmitEpisodeComment(episodeId, {
      content: data.comment.content
    })

    console.log('评论提交接口响应:', res)
    showToastMessage('评论发布成功')
  } catch (error) {
    console.error('评论提交失败:', error)
    showToastMessage('评论发布失败，请稍后重试')
  }
}

// 生命周期
onMounted(() => {
  loadVideos()
})
</script>

<style scoped>
/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  height: 30vh;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.1);
  border-top-color: #f97316;
  border-radius: 50%;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 1rem;
}

.loading-text {
  color: #d1d5db;
  font-size: 1rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 空数据状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  color: #9ca3af;
  height: 30vh;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: #6b7280;
}

.empty-text {
  font-size: 1rem;
  color: #9ca3af;
}

/* Toast提示样式 */
.toast-message {
  position: fixed;
  bottom: 5rem;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  z-index: 50;
}
</style>
